package cn.wolfcde.luowowo.website.web.controller;

import cn.wolfcde.luowowo.website.annotation.RedisParameter;
import cn.wolfcde.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.article.domain.Community;
import cn.wolfcode.luowowo.article.query.CommunityQueryObject;
import cn.wolfcode.luowowo.article.service.ICommunityService;
import cn.wolfcode.luowowo.article.vo.CommunityAnswerVO;
import cn.wolfcode.luowowo.cache.service.ICommunityRedisService;
import cn.wolfcode.luowowo.cache.vo.CommunityVO;
import cn.wolfcode.luowowo.comment.domain.CommunityAnswer;
import cn.wolfcode.luowowo.comment.query.CommunityAnswerQueryObject;
import cn.wolfcode.luowowo.comment.service.ICommunityAnswerService;
import cn.wolfcode.luowowo.common.domain.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("/community")
@Controller
public class CommunityController {

    @Value("${file.path}")
    private String filePath;

    @Reference
    private ICommunityService communityService;

    @Reference
    private ICommunityAnswerService communityAnswerService;

    @Reference
    private ICommunityRedisService communityRedisService;

    @RequestMapping("/public")
    @ResponseBody
    public Object publish(Model model, Community community, @RedisParameter UserInfo userInfo) {

        community.setUserInfo(userInfo);
        communityService.saveOrUpdate(community);
        return new AjaxResult();
    }

    @RequestMapping("/ask")
    public String ask(Model model, Community community, @RedisParameter UserInfo userInfo) {
        return "community/public";
    }

    /**
     * 我的问答列表
     * @param model
     * @param qo
     * @return
     */

    @RequestMapping("/question")
    public String questionLilist(Model model,@ModelAttribute("qo") CommunityQueryObject qo) {
        qo.setPageSize(5);
        PageInfo<Community> pageInfo = communityService.queryForList(qo);

        for (Community community : pageInfo.getList()) {
            CommunityAnswer answer = communityAnswerService.findTopByDetailId(community.getId());

            if (answer == null){
                continue;
            }

            //使用reids的数据
            CommunityVO vo = communityRedisService.getCommunityVo(community.getId());

            if(vo != null){
                community.setViewnum(vo.getViewnum());
                community.setReplynum(vo.getReplynum());
            }else {
                community.setViewnum(0);
                community.setReplynum(0);
            }

            CommunityAnswerVO answerVO = new CommunityAnswerVO();
            BeanUtils.copyProperties(answer, answerVO);
            community.setAnswerVO(answerVO);
        }

        model.addAttribute("pageInfo", pageInfo);
        return "community/wenda";
    }

    @RequestMapping("/questionDetail")
    public Object questionDetail(Model model ,CommunityAnswerQueryObject qo) {

        //回复详情
        Community community = communityService.selectById(qo.getDetailId());
        model.addAttribute("c", community);

        //回复列表
        Page page = communityAnswerService.queryPageForAnswer(qo);
        model.addAttribute("page", page);

        //增加浏览数
        communityRedisService.incrViewnum(qo.getDetailId(), 1);

        //获取浏览数据
        CommunityVO vo = communityRedisService.getCommunityVo(qo.getDetailId());

        model.addAttribute("vo", vo);

        return "community/wendaDetail";
    }

    /**
     * 社区问答详情回答保存
     */

    @RequestMapping("/answerDetailSubmit")
    @ResponseBody
    public Object answerDetailSubmit(CommunityAnswer communityAnswer, @RedisParameter UserInfo userInfo) {

        communityAnswer.setUserId(userInfo.getId());
        communityAnswer.setHeadUrl(userInfo.getHeadImgUrl());
        communityAnswer.setUsername(userInfo.getNickname());
        communityAnswer.setLevel(userInfo.getLevel());

        // BeanUtils.copyProperties(userInfo, communityAnswer);

        communityAnswerService.save(communityAnswer);

        //增加回复数
        communityRedisService.incrReplynum(communityAnswer.getDetailId(), 1);

        return new AjaxResult();
    }

    /**
     * 社区问答详情列表查询
     */

    @RequestMapping("/answerList")
    public Object answerList(Model model ,CommunityAnswerQueryObject qo) {
        Page page = communityAnswerService.queryPageForAnswer(qo);
        model.addAttribute("page", page);
        return new AjaxResult();
    }

    /**
     * 点赞更新数据
     * @param id
     * @return
     */

    @RequestMapping("/thumbup")
    @ResponseBody
    public Object thumbup(String id, @RedisParameter UserInfo userInfo) {

        if (userInfo != null && userInfo.getId() != null){
            Boolean isThumbup = communityRedisService.communityThumbup(id, userInfo.getId());
            if (isThumbup){
                AjaxResult result = new AjaxResult();
                result.setSuccess(false);
                result.setMsg("今日已操作，明日继续");
                return result;
            }
        }else if (userInfo == null){
            AjaxResult result = new AjaxResult();
            result.setSuccess(false);
            result.setCode(102);
            result.setMsg("当前操作需要登陆");
            return result;
        }

        CommunityAnswer communityAnswer = communityAnswerService.selectById(id);
        communityAnswer.setThumbupnum(communityAnswer.getThumbupnum() +1);
        communityAnswerService.save(communityAnswer);

        communityService.updateNumyById(communityAnswer.getDetailId());

        AjaxResult result = new AjaxResult();
        result.setResult(communityAnswer.getThumbupnum());
        return result;
    }

    @RequestMapping("/atten")
    @ResponseBody
    public Object atten(Long id, @RedisParameter UserInfo userInfo) {

        if (userInfo == null){
            AjaxResult result = new AjaxResult();
            result.mark("当前操作需要登陆。");
            result.setCode(102);
            return result;
        }

        Boolean isFocus = communityRedisService.incrFocusnum(id, userInfo.getId(), 1);
        CommunityVO vo = communityRedisService.getCommunityVo(id);
        AjaxResult res = new AjaxResult();
        res.setResult(vo);
        res.setSuccess(isFocus);
        return res;

    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }



}
